package com.asen.libcommon.base.viewbind

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.asen.libcommon.base.BaseFragment
import com.gyf.immersionbar.ktx.immersionBar

/**
 * @date   : 2021/2/23
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : aac模式封装 -> 下次升级为 mvvm 模式
 */
abstract class BaseViewBindFragment<VB:ViewBinding> : BaseFragment() {

    // TODO: ViewBinding绑定类
    abstract val mBinding: VB
    // TODO: viewModel绑定类
    open val mViewModel: BaseViewModel? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        lifecycleScope.launchWhenStarted {
            // TODO:注册eventBus 回调 直接在 fragment 上面调用 bindEventBus便可回调接收消息
            //  if (isOpenEventBus) bindEventBus { onEventBus(it) }
            initView(view)
            lazyLoadDataIfPrepared()
            initEvent()
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            lazyLoadDataIfPrepared()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) immersionBar()
    }

    /** 初始类 */
    protected open suspend fun initView(view: View) {}
    protected open suspend fun initEvent() {}

    /** EventBus 事件回调 */
    //protected open fun onEventBus(event: EventBusEntity) {}
    //protected open val isOpenEventBus = false // TODO:是否使用 eventBus

    /** 懒加载 */
    protected open fun lazyLoad() {}
    private fun lazyLoadDataIfPrepared() {
        if (userVisibleHint && isViewPrepare && !hasLoadData) {
            lazyLoad()
            hasLoadData = true
        }
    }

}